package com.huineta.business.common.security.process;

import com.huineta.business.common.aop.enums.Action;
import com.huineta.business.common.context.BaseContext;
import com.huineta.business.common.security.services.SecurityUser;
import com.huineta.business.common.security.uutoken.SecurityUserToken;
import com.huineta.business.common.tools.core.ServletUtil;
import com.huineta.business.common.web.domain.Result;
import com.huineta.business.common.web.domain.ResultCode;
import org.springframework.security.core.Authentication;
import com.huineta.business.common.security.uutoken.SecurityUserTokenService;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.annotation.Resource;
import java.io.IOException;

/**
 * Author:       Dmm Lee< bclassline@gmail.com >
 * Date:         2022/11/28
 * Description:  Security 登陆成功处理类
 */
@Component
public class SecureLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private BaseContext context;

    @Resource
    private SecurityUserTokenService customUserDetailsTokenService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();

            SecurityUserToken userToken = customUserDetailsTokenService.createToken(securityUser);
            String tokenKey = customUserDetailsTokenService.saveToken(userToken);
            String tokenValue = userToken.getToken();

            // 登 录 日 志
            context.record("登录","登录成功", Action.AUTH, true, "","");

            ServletUtil.writeJson(Result.success(ResultCode.LOGIN_SUCCESS,tokenKey,tokenValue));
    }
}
